package com.ea.eadp.nexus.test.pageDefinition.mobile;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.ea.eadp.nexus.test.common.SystemProperties;
import com.ea.eadp.nexus.test.common.TestUtil;
import com.ea.eadp.nexus.test.pageDefinition.TwoFactorAuthClientWithCode;

public class TFAClient_WebBasedMobile_Code extends TFAClient_WebBasedMobile
implements TwoFactorAuthClientWithCode<WebDriver> {
    public static  By SUBMIT = By.id("btnLogin");
    public static  By CODE = By.id("twofactorCode");
	public static final By RESEND_CODE = By.id("resend_code_link");
	public static final String TRUST_THIS_DEVICE = "trustThisDevice";
    public static final By SkipUpdateToAppAuth=By.id("btnCancel");
    public static final By TFASUBMIT = By.id("btnTFALogin");
    public static final String getTrustThisDeviceLabel = "label-trustThisDevice";
    private Log logger = LogFactory.getLog(getClass());

    @Override
    public void goAuthentication(String mobileDeviceId) throws Exception {
      String format = "%s/connect/auth?client_id=%s&response_type=code&display=mobile/login";
      String  url=String.format(
                format,
                TestUtil.BaseConnectURI(),
              System.getProperty(SystemProperties.ClientId)
      );
        if(mobileDeviceId != null) {
            url += String.format("&machineProfileKey=%s", mobileDeviceId);
        }
        getClient().get(url);
    }

    public void goAuthentication(String mobileDeviceId, String clientId) throws Exception {
        String format = "%s/connect/auth?client_id=%s&response_type=code&display=mobile/login";
        String  url=String.format(
                format,
                TestUtil.BaseConnectURI(),
                clientId
        );
        if(mobileDeviceId != null) {
            url += String.format("&machineProfileKey=%s", mobileDeviceId);
        }
        getClient().get(url);
    }

    @Override
    public void login(String username, String password) throws Exception {
        getClient().findElement(USERNAME).clear();
        getClient().findElement(USERNAME).sendKeys(username);
        getClient().findElement(PASSWORD).clear();
        getClient().findElement(PASSWORD).sendKeys(password);
        try{
        getClient().findElement(SUBMIT).click();
        }catch (NoSuchElementException e){
            getClient().findElement( By.cssSelector("input.fut-btn")).click();
        }

    }

    @Override
	public void respondToChallenge(String answer) throws Exception {
        WebDriverWait wait = new WebDriverWait(getClient(), 30, 1000);
        wait.until(ExpectedConditions.visibilityOfElementLocated(CODE));
        getClient().findElement(CODE).clear();
        getClient().findElement(CODE).sendKeys(answer);
        try {
            getClient().findElement(TFASUBMIT).click();
        }catch (NoSuchElementException e){
            getClient().findElement(By.id("btnTFAVerify")).click();

        }
	}

	@Override
	public void askResendCode() throws Exception {
		getClient().findElement(RESEND_CODE).click();
	}

	@Override
	public Status getStatus() throws Exception {
		Status result = super.getStatus();

		if (Status.UNKNOWN == result) {
			try {
				getClient().findElement(By.cssSelector("input#twofactorCode"));
				return Status.CHALLENGING_AUTH;
			} catch (NoSuchElementException e) {

			}
		}

		return result;
	}

    public boolean verifyCheckedTrustThisDeviceBox(){
        WebElement element =  getClient().findElement(By.cssSelector("label#"+getTrustThisDeviceLabel));
        WebElement elementCheckBox = getClient().findElement(By.id(TRUST_THIS_DEVICE));
        /* JavascriptExecutor js = (JavascriptExecutor)getClient();
        Object checked=js.executeScript("return $('trustThisDevice')[0].checked");*/
        return elementCheckBox.isSelected();
    }
    public void clickTrustThisDevice(boolean checkTrustThisDevice) {
        WebElement element = getClient().findElement(By.cssSelector("input#"+TRUST_THIS_DEVICE));
        if((checkTrustThisDevice && (!element.isSelected()))
				|| (!checkTrustThisDevice && (element.isSelected()))){
            getClient().findElement(By.cssSelector("div.origin-ux-checkbox-control.origin-ux-control>span")).click();
		}
	}

    public void skipUpdateToAppAuth() {
        try{
            WebDriverWait wait = new WebDriverWait(getClient(), 5);
            wait.until(ExpectedConditions.visibilityOfElementLocated(SkipUpdateToAppAuth));
            getClient().findElement(SkipUpdateToAppAuth).click();
        } catch (TimeoutException e) {
            logger.warn("not find Element"+SkipUpdateToAppAuth);
        }
    }
}
